package com.example.travelgd.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.travelgd.entity.News;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface NewsMapper extends BaseMapper<News> {

    /**
     * 分页查询已发布的动态
     */
    @Select("SELECT * FROM news WHERE status = 1 " +
            "ORDER BY create_time DESC LIMIT #{offset}, #{pageSize}")
    List<News> selectAllPublishedWithPage(
            @Param("offset") Integer offset,
            @Param("pageSize") Integer pageSize);

    /**
     * 查询所有已发布的动态
     */
    @Select("SELECT * FROM news WHERE status = 1 ORDER BY create_time DESC")
    List<News> selectAllPublished();

    /**
     * 获取已发布动态的总数
     */
    @Select("SELECT COUNT(*) FROM news WHERE status = 1")
    Integer countAllPublished();

    /**
     * 增加阅读数
     */
    @Update("UPDATE news SET read_count = read_count + 1 WHERE id = #{id}")
    void incrementReadCount(@Param("id") Long id);

    /**
     * 按时间范围查询动态
     */
    @Select("SELECT * FROM news WHERE status = 1 " +
            "AND create_time BETWEEN #{startTime} AND #{endTime} " +
            "ORDER BY create_time DESC")
    List<News> selectByTimeRange(
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);

    /**
     * 查询热门动态(阅读数前N)
     */
    @Select("SELECT * FROM news WHERE status = 1 " +
            "ORDER BY read_count DESC LIMIT #{limit}")
    List<News> selectHotNews(@Param("limit") Integer limit);

    /**
     * 按来源查询动态
     */
    @Select("SELECT * FROM news WHERE status = 1 AND source = #{source} " +
            "ORDER BY create_time DESC")
    List<News> selectBySource(@Param("source") String source);
}